package com.fsh.lingsp.common.user.service.adapter;

import cn.hutool.core.bean.BeanUtil;
import com.fsh.lingsp.common.common.domain.enums.YseOrNoEnum;
import com.fsh.lingsp.common.user.domain.entity.ItemConfig;
import com.fsh.lingsp.common.user.domain.entity.User;
import com.fsh.lingsp.common.user.domain.entity.UserBackpack;
import com.fsh.lingsp.common.user.domain.vo.resp.user.BadgeResp;
import com.fsh.lingsp.common.user.domain.vo.resp.user.UserInfoResp;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class UserAdapter {


    public static User buildAuthorizeUser(Long id, WxOAuth2UserInfo userInfo) {
        User user = User.builder()
                .id(id)
                .avatar(userInfo.getHeadImgUrl())
                .name(userInfo.getNickname())
                .build();
        return user;
    }

    public static UserInfoResp buildUserInfoResp(User user, Integer modifyNameChance) {
        UserInfoResp userInfoResp = new UserInfoResp();
        BeanUtil.copyProperties(user, userInfoResp);
        userInfoResp.setModifyNameChance(modifyNameChance);
        return userInfoResp;
    }

    public static List<BadgeResp> buildBadgeResp(List<ItemConfig> itemConfigList,
                                                 List<UserBackpack> userBackpackList,
                                                 User user) {
        //取出用户 拥有的徽章item_id合集
        List<Long> haveItems = userBackpackList.stream().map(UserBackpack::getItemId).collect(Collectors.toList());

        //对每个徽章操作
        return itemConfigList.stream().map(item -> {
            BadgeResp badgeResp = new BadgeResp();
            BeanUtil.copyProperties(item, badgeResp);
            //用户是否拥有这枚徽章
            badgeResp.setObtain(haveItems.contains(item.getId()) ? YseOrNoEnum.YES.getStatus() : YseOrNoEnum.NO.getStatus());
            //用户是否佩戴这枚徽章
            badgeResp.setWearing(Objects.equals(item.getId(), user.getItemId()) ? YseOrNoEnum.YES.getStatus() : YseOrNoEnum.NO.getStatus());
            return badgeResp;
        }).sorted(Comparator.comparing(BadgeResp::getWearing, Comparator.reverseOrder())
                .thenComparing(BadgeResp::getObtain, Comparator.reverseOrder()))
                .collect(Collectors.toList());
    }
}
